package lesson23;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class MyCondition {

    public static void main(String[] args) {

        ReentrantLock lock = new ReentrantLock();

        Condition condition = lock.newCondition();

        ExecutorService executorService = Executors.newFixedThreadPool(5);

        for(int i = 0; i< 5; i++){
            executorService.submit(new Task1(lock, condition));
        }
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for(int i = 0; i< 5; i++){
            executorService.submit(new Task2(lock, condition));
        }
    }

}

class Task1 implements Runnable{

    private ReentrantLock lock;

    private Condition condition;

    public Task1(ReentrantLock lock, Condition condition){
        this.lock = lock;
        this.condition = condition;
    }

    @Override
    public void run() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + " 等待执行...");
            condition.await();
            System.out.println(Thread.currentThread().getName() + " 收到通知执行完成...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}

class Task2 implements Runnable{

    private ReentrantLock lock;

    private Condition condition;

    public Task2(ReentrantLock lock, Condition condition){
        this.lock = lock;
        this.condition = condition;
    }

    @Override
    public void run() {
        lock.lock();
        try {
            Thread.sleep(5000);
            System.out.println("条件已满足，通知业务执行");
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}